package com.wy.springbootblog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ser.std.RawSerializer;
import com.wy.springbootblog.mapper.ArticleMapper;
import com.wy.springbootblog.mapper.CommentMapper;
import com.wy.springbootblog.pojo.Article;
import com.wy.springbootblog.pojo.Comment;
import com.wy.springbootblog.pojo.Result;
import com.wy.springbootblog.pojo.SearchBean;
import com.wy.springbootblog.service.CommentService;
import com.wy.springbootblog.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper,Comment> implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private CommentService commentService;

    // 新增评论
    @Override
    public Result<Void> saveComment(Comment comment) {
        // 1.查询文章是否存在
        Article article = articleMapper.selectOne(new LambdaQueryWrapper<Article>().eq(Article::getId, comment.getArticleId()).eq(Article::getFlag, 0));
        if (article == null) {
            return Result.error("文章id不存在");
        }
        // 2.查询父评论id是否存在
        if (comment.getParentId() != null) {
            // 有父评论
            Comment commentQuery = commentMapper.selectOne(new LambdaQueryWrapper<Comment>().eq(Comment::getId, comment.getParentId()).eq(Comment::getFlag, 0));
            if (commentQuery == null) {
                return Result.error("父评论parentId不存在");
            }
        }
        // 3.拿到用户id
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        comment.setCreateTime(LocalDateTime.now());
        comment.setUpdateTime(LocalDateTime.now());
        comment.setUserId(userId);
        comment.setFlag(0);
        Integer rows = commentMapper.insert(comment);
        if (rows > 0) {
            return Result.success();
        }
        return Result.error("新增评论失败");
    }

    // 删除评论
    @Override
    public Result<Void> deleteComment(Integer id) {
        // 1.判断用户身份权限
        Map<String, Object> map = ThreadLocalUtil.get();
        String role = (String) map.get("role");
        if (!Objects.equals(role, "admin")) {
            // 没有删除评论权限
            return Result.error("该用户无删除评论权限");
        }
        // 2.判断评论是否存在
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getId, id);
        queryWrapper.eq(Comment::getFlag, 0);
        Comment comment = commentMapper.selectOne(queryWrapper);
        if (comment == null) {
            return Result.error("评论不存在");
        }
        // 3.删除本身评论
        Comment commentUpdate = new Comment();
        commentUpdate.setId(id);
        commentUpdate.setFlag(1);
        commentUpdate.setUpdateTime(LocalDateTime.now());
        commentMapper.updateById(commentUpdate);
        // 4.删除以本评论的全部子评论 (有子评论的评论)
        // 删除一级评论
        if (comment.getParentId() == null) {
            List<Comment> commentList = commentMapper.selectList(new LambdaQueryWrapper<Comment>().eq(Comment::getParentId, comment.getId()).eq(Comment::getFlag, 0));
            List<Comment> commentListUpdate = new ArrayList<>();
            for (int i = 0; i < commentList.size(); i++) {
                Comment commentChildren = new Comment();
                commentChildren.setId(commentList.get(i).getId());
                commentChildren.setFlag(1);
                commentChildren.setUpdateTime(LocalDateTime.now());
                commentListUpdate.add(commentChildren);
            }
            // 删除二级评论
            commentService.saveOrUpdateBatch(commentListUpdate);
        }
        return Result.success();
    }

    // 分页查询评论
    @Override
    public Result commentList(SearchBean<Comment> searchBean) {
        Page<Comment> page = new Page<>(searchBean.getPageNum(), searchBean.getPageSize());
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Comment::getCreateTime); // 按创建时间降序排列
        queryWrapper.eq(Comment::getFlag, 0);
        Page<Comment> commentPageOne = commentMapper.selectPage(page, queryWrapper);
        List<Comment> commentListOne = commentPageOne.getRecords();
        if (commentListOne != null && !commentListOne.isEmpty()) {
            // 遍历一级评论
            for (int i = 0; i < commentListOne.size(); i++) {
                List<Comment> commentListTwo = commentMapper.selectList(new LambdaQueryWrapper<Comment>()
                        .eq(Comment::getParentId, commentListOne.get(i).getId())
                        .eq(Comment::getFlag, 0)
                        .orderByDesc(Comment::getCreateTime)
                );
                commentListOne.get(i).setChildren(commentListTwo);
            }
        }
        // 过滤掉二级评论，之所以没有在一级查询时添加条件，是为了拿到total总数
        List<Comment> ResultList = commentListOne.stream().filter(item -> item.getParentId() == null).collect(Collectors.toList());
        return Result.success(ResultList, commentPageOne.getTotal());
    }

    // 修改评论
    @Override
    public Result<Void> updateComment(Comment comment) {
        // 1.判断用户身份权限
        Map<String, Object> map = ThreadLocalUtil.get();
        String role = (String) map.get("role");
        if (!Objects.equals(role, "admin")) {
            // 没有修改评论权限
            return Result.error("该用户无修改评论权限");
        }
        if (comment.getId() == null) {
            return Result.error("评论id不能为空");
        }
        // 2.判断评论是否存在
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getId, comment.getId());
        queryWrapper.eq(Comment::getFlag, 0);
        Comment commentQuery = commentMapper.selectOne(queryWrapper);
        if (commentQuery == null) {
            return Result.error("评论不存在");
        }
        // 3.修改评论
        comment.setUpdateTime(LocalDateTime.now());
        Integer rows = commentMapper.updateById(comment);
        if (rows > 0) {
            return Result.success();
        }
        return Result.error("修改评论失败");
    }
}
